<script lang="ts" setup name="message">
import { computed, nextTick, onActivated, onDeactivated, ref, watch } from 'vue'
import { Search } from '@vicons/ionicons5'
import TitleBar from '../../../components/TitleBar.vue'
import MessageListItem from '../../../components/MessageListItem.vue'
import MessageContextItem from '../../../components/MessageContextItem.vue'
import { useUserMessageList } from '@renderer/store/userMessage.store'
import { useMessageUserList } from '@renderer/store/messageUser.store'
import { initTime } from '@renderer/utils/time'
import { requestPost } from '@renderer/utils/commonRequest'
import { Message, UserMessage } from '@renderer/types'
import { useUserInfoStore } from '@renderer/store/useUserInfo.store'
import { useRoute } from 'vue-router'

const route = useRoute()
const search = ref<string>('')
const messageValue = ref<string>('')

const userMessageListStore = useUserMessageList()
const messageUserListStore = useMessageUserList()

const userInfo = computed(() => {
  return useUserInfoStore().getUserInfo
})

const userList = computed(() => {
  if (search.value == '') return messageUserListStore.getUserList
  return messageUserListStore.getUserList.filter((item) => {
    if (item.user.cetName.indexOf(search.value) != -1) return true
    return false
  })
})

const selectUserId = computed(() => {
  return userMessageListStore.getGetSelectUserId
})

const messageList = computed(() => {
  return userMessageListStore.getUserMessage?.messages ?? []
})

onActivated(() => {
  if (!route.query.friendId) return
  const friendId = route.query.friendId as string
  userClick(friendId)
})

onDeactivated(() => {
  userMessageListStore.selectUserId = ''
  userMessageListStore.userMessage = null
})

const selectUser = computed(() => {
  return (
    userMessageListStore.getUserMessage?.friend ?? {
      id: '',
      userName: '',
      passWord: '',
      cetName: '',
      mobile: '',
      eMail: '',
      headPhoto: ''
    }
  )
})

const userClick = async (friendId: string): Promise<void> => {
  const data = await requestPost<UserMessage>('/userMessage', {
    friendId: friendId,
    userId: userInfo.value?.id
  })
  if (!data) return
  userMessageListStore.setSelectUserId(friendId)
  userMessageListStore.setUserMessage(data)
  const flg = messageUserListStore.getUserList.map((item) => {
    if (item.user.id == friendId) item.isWei = 0
    return item
  })
  messageUserListStore.setUserList(flg)
}

const sendClick = async (): Promise<void> => {
  if (messageValue.value == '') return
  const data = await requestPost<boolean>('/userMessage/sendMessage', {
    sendUserId: userInfo.value?.id ?? '',
    onUserId: selectUserId.value,
    context: messageValue.value,
    type: 'text'
  })
  if (!data) return
  const messageUtils: Message = {
    context: messageValue.value,
    type: 'text',
    createdTime: new Date().toString(),
    sendUserId: userInfo.value?.id ?? ''
  }
  messageUserListStore.setUserList(
    messageUserListStore.getUserList.map((item) => {
      if (item.user.id == selectUserId.value)
        item.message = {
          ...messageUtils,
          id: '',
          updatedTime: ''
        }
      return item
    })
  )
  userMessageListStore.setMessageListItem(messageUtils)
  messageValue.value = ''
}

watch(
  () => useUserMessageList().getUserMessage?.messages.length,
  () => {
    nextTick(() => {
      const ele = document.getElementById('my_scorll')!
      if (ele && ele.children.length) {
        ele.children[0].scrollTop = ele.children[0].scrollHeight
      }
    })
  }
)
</script>

<template>
  <div class="message">
    <div class="left">
      <div class="search_box">
        <n-input v-model:value="search" type="text" placeholder="搜索" size="small">
          <template #prefix> <n-icon :component="Search" /> </template
        ></n-input>
      </div>
      <div class="user_list">
        <n-scrollbar>
          <MessageListItem
            v-for="item in userList"
            :key="item.user.id"
            :url="item.user.headPhoto"
            :cet-name="item.user.cetName"
            :context="item.message.context"
            :cont="item.isWei"
            :time="initTime(item.message.createdTime)"
            :class="{ active: selectUserId == item.user.id }"
            @click="userClick(item.user.id)"
          ></MessageListItem>
        </n-scrollbar>
      </div>
    </div>
    <div class="right">
      <TitleBar class="title_bar"></TitleBar>
      <div v-if="selectUserId" class="message_box">
        <div class="cetName">{{ selectUser.cetName }}</div>
        <div class="message_context">
          <n-scrollbar id="my_scorll" trigger="none">
            <MessageContextItem
              v-for="item in messageList"
              :key="item.createdTime"
              :face-img="item.sendUserId == selectUserId
                ? selectUser.headPhoto
                : userInfo!.headPhoto"
              :message="item.context"
              :position="
                item.type == 'system'
                  ? 'center'
                  : item.sendUserId == selectUserId
                  ? 'left'
                  : 'right'
              "
            ></MessageContextItem>
          </n-scrollbar>
        </div>
        <div class="chat_box">
          <div class="input_box">
            <n-input
              v-model:value="messageValue"
              placeholder="请输入内容......"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 2 }"
            />
          </div>
          <n-button tertiary type="success" @click="sendClick"> 发送消息 </n-button>
        </div>
      </div>
      <div v-else class="context">
        <n-empty description="暂无数据"> </n-empty>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.message {
  display: flex;
  justify-content: space-between;
  height: 100%;
  .left {
    width: 250px;
    border-right: 1px solid #d6d6d6;

    .search_box {
      height: 50px;
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 5%;
      .n-input {
        -webkit-app-region: no-drag;
        background-color: #e2e2e2;
        border: none !important;
        &:focus-within {
          background-color: #fff;
        }
      }
    }
    .user_list {
      height: calc(100% - 60px);
      background-color: #e6e6e7;
    }
  }
  .right {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: relative;
    background: #f5f5f5;
    .title_bar {
      position: absolute;
      right: 0;
      top: 0;
    }
    .message_box {
      height: 100%;
      display: flex;
      flex-direction: column;
      .cetName {
        height: 59px;
        padding-left: 20px;
        display: flex;
        align-items: center;
        font-size: 16px;
        border-bottom: 1px solid #eae8e7;
      }
      .message_context {
        -webkit-app-region: no-drag;
        height: calc(100% - 150px);
      }
      .chat_box {
        -webkit-app-region: no-drag;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        border-top: 1px solid #eae8e7;
        height: 110px;
        justify-content: space-between;
        .input_box {
          width: 100%;
          flex: 1;
          .n-input {
            background-color: transparent;
          }
        }
        .n-button {
          margin: 10px 20px;
        }
        :deep(.n-input__border) {
          display: none;
        }
      }
    }
    .context {
      display: flex;
      align-items: center;
      flex: 1;
      justify-content: center;
    }
  }
}
</style>
